package com.flyox.game.fivetiger.view;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

import com.flyox.game.fivetiger.bean.CONSTS;
import com.flyox.game.fivetiger.bean.LayoutPlayer;
import com.flyox.game.fivetiger.control.FivetigerControl;

/**
 * 主画面
 * 
 * @author sunwei
 * 
 */
public class FivetigerJFrame extends javax.swing.JFrame implements Observer {

	private static final long serialVersionUID = 5076740131535195380L;
	FivetigerControl control;

	public JButton jButtonCreate;
	public JLabel jLabelTeamFlag;

	public JButton jButtonRequestDogfall;
	public JButton jButtonUndo;
	public JComboBox jComboBoxIP;
	public JButton jButtonGiveUp;
	public LayoutJPanel layoutJPanel;

	private JLabel jLabelState;
	private JPanel jPanelControl;

	BufferedImage zeroImage = null;
	BufferedImage threeImage = null;
	BufferedImage zerotThreeImage = null;
	BufferedImage threeZeroImage = null;
	BufferedImage iconImage = null;

	JMenuItem helpItem;
	JMenuItem playLayoutItem;
	JMenuItem stopLayoutItem;
	ComboButton helpComboButton;

	JMenuItem exitSystemItem;
	public JMenuItem disConnectItem;
	ComboButton exitComboButton;

	LayoutPlayer layoutPlayer;
	private static String MENU_HELP = "帮助";
	private static String MENU_PLAY = "演示";
	private static String MENU_STOP = "停止";

	private static String MENU_LOGOUT = "退出";
	private static String MENU_DISCONNECT = "断开";

	public FivetigerJFrame(FivetigerControl control) {
		super();
		this.control = control;
		initRes();
		initGUI();
	}

	private void initRes() {
		try {
			zeroImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/fivetiger/res/zero.png"));
			threeImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/fivetiger/res/three.png"));
			zerotThreeImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/fivetiger/res/zero_three.png"));
			threeZeroImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/fivetiger/res/three_zero.png"));
			iconImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/fivetiger/res/fivetiger.png"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	private void initGUI() {
		try {
			setTitle("棋类游戏->五虎<-www.flyox.com");
			this.setIconImage(iconImage);
			// this.setUndecorated(true);
			addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					dispose();
					System.exit(0);
				}
			});
			setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			{
				layoutJPanel = new LayoutJPanel(control);
				getContentPane().add(layoutJPanel, BorderLayout.CENTER);
				layoutJPanel.setBackground(new java.awt.Color(191, 202, 230));
			}
			{
				jPanelControl = new JPanel();
				getContentPane().add(jPanelControl, BorderLayout.EAST);
				jPanelControl.setLayout(null);
				jPanelControl.setPreferredSize(new java.awt.Dimension(200, 600));
				jPanelControl.setBackground(new java.awt.Color(115, 136, 193));
				{
					jButtonCreate = new JButton();
					jPanelControl.add(jButtonCreate);
					jButtonCreate.setText("\u521b\u5efa\u6e38\u620f");
					jButtonCreate.setBounds(12, 36, 100, 22);
					jButtonCreate.setToolTipText("\u521b\u5efa\u670d\u52a1\u5668");
					jButtonCreate.setBackground(new java.awt.Color(252, 245, 76));
					jButtonCreate.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							jButtonCreateActionPerformed(evt);
						}
					});
				}
				{
					ComboBoxModel jComboBoxIPModel = new DefaultComboBoxModel(new String[] { "加入游戏"});
					jComboBoxIP = new JComboBox();
					jComboBoxIP.setModel(jComboBoxIPModel);
					jPanelControl.add(jComboBoxIP);
					jComboBoxIP.setBounds(12, 77, 100, 22);
					jComboBoxIP.setToolTipText("\u70b9\u51fb\u67e5\u8be2\u670d\u52a1\u5668\u5e76\u8fde\u63a5");
					jComboBoxIP.setBackground(new java.awt.Color(252, 245, 76));
					jComboBoxIP.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							if (jComboBoxIP.getSelectedIndex() != 0) {
								control.connectDataTrafficServer((String) jComboBoxIP.getSelectedItem());
							}
						}
					});
					jComboBoxIP.addPopupMenuListener(new PopupMenuListener() {
						public void popupMenuWillBecomeVisible(PopupMenuEvent evt) {
							control.queryDataTrafficServers();
						}

						public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) {
						}

						public void popupMenuCanceled(PopupMenuEvent evt) {
						}
					});
				}
				{
					jLabelState = new JLabel();
					jPanelControl.add(jLabelState);
					jLabelState.setBounds(12, 157, 100, 22);
				}
				{
					jButtonUndo = new JButton();
					jPanelControl.add(jButtonUndo);
					jButtonUndo.setText("\u6094\u68cb");
					jButtonUndo.setBounds(12, 237, 100, 22);
					jButtonUndo.setBackground(new java.awt.Color(252, 245, 76));
					jButtonUndo.setEnabled(false);
					jButtonUndo.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							if(control.getDoc().isSteptsNull()){
								return ;
							}
							jButtonUndo.setEnabled(false);
							control.sendUndoRequest();
						}
					});
				}
				{
					jButtonRequestDogfall = new JButton();
					jPanelControl.add(jButtonRequestDogfall);
					jButtonRequestDogfall.setText("\u6c42\u548c");
					jButtonRequestDogfall.setBounds(13, 277, 100, 22);
					jButtonRequestDogfall.setEnabled(false);
					jButtonRequestDogfall.setBackground(new java.awt.Color(252, 245, 76));
					jButtonRequestDogfall.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							if(control.getDoc().isSteptsNull()){
								return ;
							}
							jButtonRequestDogfall.setEnabled(false);
							control.sendRequestDogfall();
						}
					});
				}
				{
					jButtonGiveUp = new JButton();
					jPanelControl.add(jButtonGiveUp);
					jButtonGiveUp.setText("\u6295\u964d");
					jButtonGiveUp.setBounds(13, 316, 100, 22);
					jButtonGiveUp.setEnabled(false);
					jButtonGiveUp.setBackground(new java.awt.Color(252, 245, 76));
					jButtonGiveUp.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, "确定要投降？", "提示", JOptionPane.YES_NO_OPTION)) {
								control.sendGiveUp();
							}
						}
					});
				}
				{
					jLabelTeamFlag = new JLabel();
					jPanelControl.add(jLabelTeamFlag);
					jLabelTeamFlag.setBounds(40, 379, 40, 40);
				}
				{
					helpItem = new JMenuItem(MENU_HELP);
					helpItem.setPreferredSize(new Dimension(100, 22));
					helpItem.setAction(new ComboButtonAction(MENU_HELP));
					playLayoutItem = new JMenuItem(MENU_PLAY);
					playLayoutItem.setPreferredSize(new Dimension(100, 22));
					playLayoutItem.setAction(new ComboButtonAction(MENU_PLAY));
					stopLayoutItem = new JMenuItem(MENU_STOP);
					stopLayoutItem.setPreferredSize(new Dimension(100, 22));
					stopLayoutItem.setAction(new ComboButtonAction(MENU_STOP));
					stopLayoutItem.setEnabled(false);
					JMenuItem[] items = new JMenuItem[] { helpItem, playLayoutItem, stopLayoutItem };

					helpComboButton = new ComboButton();
					helpComboButton.initAction(items);
					helpComboButton.setBounds(12, 466, 100, 22);
					jPanelControl.add(helpComboButton);
					helpComboButton.setBackground(new java.awt.Color(252, 245, 76));
				}
				{
					exitSystemItem = new JMenuItem(MENU_LOGOUT);
					exitSystemItem.setPreferredSize(new Dimension(100, 22));
					exitSystemItem.setAction(new ComboButtonAction(MENU_LOGOUT));
					disConnectItem = new JMenuItem(MENU_DISCONNECT);
					disConnectItem.setPreferredSize(new Dimension(100, 22));
					disConnectItem.setAction(new ComboButtonAction(MENU_DISCONNECT));
					disConnectItem.setEnabled(false);
					JMenuItem[] exitItems = new JMenuItem[] { exitSystemItem, disConnectItem };

					exitComboButton = new ComboButton();
					exitComboButton.initAction(exitItems);
					exitComboButton.setBounds(12, 510, 100, 22);
					jPanelControl.add(exitComboButton);
					exitComboButton.setBackground(new java.awt.Color(252, 245, 76));
				}
			}
			pack();
			this.setResizable(false);
			this.setSize(808, 634);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void changeToConnectStat(){
		jButtonCreate.setEnabled(false);
		jComboBoxIP.setEnabled(false);
		disConnectItem.setEnabled(true);
		exitComboButton.refreshButtons();
		stopLayoutItem.setEnabled(false);
		playLayoutItem.setEnabled(false);
		helpComboButton.refreshButtons();
		helpComboButton.updateMainButton(helpItem);
	}
	
	/**
	 * 开始游戏
	 */
	public void changeToBeginState() {
		jButtonCreate.setEnabled(false);
		jComboBoxIP.setEnabled(false);
		jButtonUndo.setEnabled(true);
		jButtonRequestDogfall.setEnabled(true);
		jButtonGiveUp.setEnabled(true);

		disConnectItem.setEnabled(true);
		stopLayoutItem.setEnabled(false);
		playLayoutItem.setEnabled(false);
		helpComboButton.refreshButtons();
		helpComboButton.updateMainButton(helpItem);
	}
	
	/**
	 * 创建游戏时的动作
	 * 
	 * @param evt
	 */
	private void jButtonCreateActionPerformed(ActionEvent evt) {
		ChessOptionsJDialog inst=new ChessOptionsJDialog(control,control.getDoc().getChessOptions(),true);
		inst.setLocationRelativeTo(null);
		inst.setVisible(true);
		
		layoutJPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		changeToConnectStat();
		control.createDataTrafficServer();
		control.createBoardServer();
	}

	/**
	 * 监听者接收请求
	 */
	public void update(Observable o, Object arg) {
		String changeFlag = (String) arg;
		if (CONSTS.FLAG_CHANGE_LAYOUT.equals(changeFlag)) {
			this.layoutJPanel.reDrawLayout();
		} else if (CONSTS.FLAG_CHANGE_STATE.equals(changeFlag)) {
			String msg = control.utilBean.getStateMsg(control.getDoc().isCurrentPlayerPlay(), control.getDoc().getCurrentState());
			jLabelState.setText(msg);
		} else if (CONSTS.FLAG_CHANGE_STATE_MSG.equals(changeFlag)) {
			jLabelState.setText(control.getDoc().getStateMsg());
		} else if (CONSTS.FLAG_CHANGE_CURRENT_PLAYER.equals(changeFlag)) {
			if (control.getDoc().isCurrentPlayerPlay()) {
				layoutJPanel.setCursor(Cursor.getDefaultCursor());
			} else {
				layoutJPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			}
		} else if (CONSTS.FLAG_CHANGE_PLAYER.equals(changeFlag)) {
			if (control.getDoc().getName().equals(CONSTS.SYS_CLIENT_NAME)) {
				jLabelTeamFlag.setIcon(new ImageIcon(threeImage));
			} else {
				jLabelTeamFlag.setIcon(new ImageIcon(zeroImage));
			}
		}
	}

	/**
	 * 断开连接
	 */
	public void conClosed() {
		jButtonCreate.setEnabled(true);
		jComboBoxIP.setEnabled(true);
		jButtonUndo.setEnabled(false);
		jButtonRequestDogfall.setEnabled(false);
		jButtonGiveUp.setEnabled(false);

		jLabelTeamFlag.setIcon(null);
		disConnectItem.setEnabled(false);
		exitComboButton.refreshButtons();
		// exitComboButton.updateMainButton(disConnectItem);

		stopLayoutItem.setEnabled(false);
		playLayoutItem.setEnabled(true);
		helpComboButton.refreshButtons();
		// helpComboButton.updateMainButton(helpItem);
	}

	/**
	 * 在选择服务器的下拉框中添加ip
	 * 
	 * @param ip
	 */
	public void addIP(String ip) {
		if (ip != null && !"".equals(ip)) {
			ComboBoxModel mode = jComboBoxIP.getModel();
			boolean same = false;
			for (int i = 0; i < mode.getSize(); i++) {
				String e = (String) mode.getElementAt(i);
				if (e.equals(ip)) {
					same = true;
					break;
				}
			}
			if (!same && mode.getSize() < 100) {
				jComboBoxIP.addItem(ip);
				disConnectItem.setEnabled(true);
			}
		}
	}

	/**
	 * 控件处理动作
	 * 
	 * @author sunwei
	 * 
	 */
	class ComboButtonAction extends AbstractAction {
		private static final long serialVersionUID = -5710015487947484336L;
		private String name;

		public ComboButtonAction(String name) {
			super(name);
			this.name = name;
		}

		public void actionPerformed(ActionEvent e) {
			if (name.equals(MENU_HELP)) {
				helpComboButton.updateMainButton(helpItem);
				HelpJDialog inst = new HelpJDialog(control.getView());
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			} else if (name.equals(MENU_PLAY)) {
				stopLayoutItem.setEnabled(true);
				playLayoutItem.setEnabled(false);
				helpComboButton.refreshButtons();
				helpComboButton.updateMainButton(stopLayoutItem);

				jButtonCreate.setEnabled(false);
				jComboBoxIP.setEnabled(false);
				layoutPlayer = new LayoutPlayer(control);
				layoutPlayer.play();
			} else if (name.equals(MENU_STOP)) {
				layoutPlayer.stop();
				stopLayoutItem.setEnabled(false);
				playLayoutItem.setEnabled(true);
				helpComboButton.refreshButtons();
				helpComboButton.updateMainButton(playLayoutItem);
			} else if (name.equals(MENU_LOGOUT)) {
				// if(control.isLive()){
				// control.sendCMD(CONSTS.CMD_LOGOUT);
				try{
					control.close();
				}catch(Exception e2){}
				// }
				dispose();
				System.exit(-1);
			} else if (name.equals(MENU_DISCONNECT)) {
				control.close();
			}
		}
	}

}
